package cn.rumoss.nettytest.time.pojo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class TimeClient{
  
  public static void main(String[] args) throws Exception {
    
    String host = "127.0.0.1";
    int port = 8080;
    EventLoopGroup workerGroup = new NioEventLoopGroup();// 只指定了一个EventLoopGroup，既是‘boss’线程，也是‘workder’线程
    
    try{
      
      Bootstrap boot = new Bootstrap();
      boot.group(workerGroup)
        .channel(NioSocketChannel.class)
        .option(ChannelOption.SO_KEEPALIVE,true)
        .handler(new ChannelInitializer<SocketChannel>(){
          @Override
          protected void initChannel(SocketChannel ch) throws Exception{
            // ch.pipeline().addLast(new TimeClientHandler());
            
            // 方案一：构造一个内部的可积累的缓冲
            // ch.pipeline().addLast(new TimeClientAllocHandler());
            // 方案二：可以把一整个ChannelHandler拆分成多个模块以减少应用的复杂程度，
            //比如你可以把TimeClientHandler拆分成2个处理器
            ch.pipeline().addLast(new TimeDecoder(),new TimeClientHandler());
            
          }
        });
      
      // 启动Client
      ChannelFuture f = boot.connect(host,port).sync();
      
      // 等到连接关闭
      f.channel().closeFuture().sync();
      
    }finally{
      workerGroup.shutdownGracefully();
    }
    
  }
  
}
